import config from "../base/profile/config.json";
import store from "../store";
import requestApi from "./requestApi";

window.APP = {
  sessionId: "",
  AndroidSDK: "",
  serverUrl: "",
  urlParam: "",
  statusBarHeight: 0
};

window.CommonUtil = {
  /**
   * 图片url处理（如果url中带有域名，则去除url中的域名，拼接上传入的域名configHost）
   * @param {*} url 图片地址
   * @param {*} configHost 域名
   */
  imgUrlFormate: function (url, configHost) {
    if (url && url.indexOf("http") != -1) {
      var index = CommonUtil.find(url, "/", 2);
      if (configHost) {
        return configHost + "" + url.substr(index);
      } else {
        return url.substr(index);
      }
    } else {
      if (url && configHost) {
        return configHost + "" + url;
      } else {
        return url;
      }
    }
  },
  imgUrlResize: function (type, h, w) {
    return `x-oss-process=image/resize,${type},h_${h},w_${w}`
  },
  // 获取一个字符串值在指定字符串第n次出现的位置
  find: function (str, cha, num) {
    var x = str.indexOf(cha);
    for (var i = 0; i < num; i++) {
      x = str.indexOf(cha, x + 1);
    }
    return x;
  },
  /**
   * 判断数组
   * @param o
   * @returns {boolean}
   */
  isArray: function (o) {
    return Object.prototype.toString.call(o) === "[object Array]";
  },

  /**
   * 自动去除数字最后的0或小数点
   * @param num
   * @param digit 保留小数点位数，默认2位
   * @returns string
   */
  fixNumber: function (num, digit) {
    if (num === "" || isNaN(num)) {
      return num;
    }
    if (typeof digit === "undefined") {
      digit = 2;
    }
    var result = parseFloat(num).toFixed(digit);
    while (result.charAt(result.length - 1) === "0") {
      result = result.substring(0, result.length - 1);
    }
    if (result.charAt(result.length - 1) === ".") {
      result = result.substring(0, result.length - 1);
    }
    return result;
  },

  /**
	    判断对象是否为空或者空字符串(多个空格也算是空字符串)
	 **/
  isEmpty: function (obj) {
    if(CommonUtil.isArray(obj)) {
      return !obj.length
    }
    if (obj == null || obj == undefined || obj == "" || obj.replace(/(^s*)|(s*$)/g, "").length == 0) {
      return true;
    } else {
      return false;
    }
  },
  /**
   * 部分隐藏手机号
   * @param  {String} mobile 手机号
   * @return {String}        中间四位星号代替
   */
  secretShowMobile: function (mobile) {
    return mobile.substr(0, 3) + "****" + mobile.substr(-4);
  },
  /**
   * 校验手机号是否合法
   * @param mobile
   * @returns {boolean}
   */
  checkMobile: function (mobile) {
    if (!mobile) {
      return false;
    }
    if (mobile.length < 11) {
      return false;
    }
    if (mobile.length > 11) {
      return false;
    }
    if (isNaN(mobile)) {
      return false;
    }
    if (new RegExp(/^1\d{10}$/).test(mobile)) {
      return true;
    }
    return false;
  },
  /**
   * 校验手机号是否合法
   * @param mobile
   * @returns {boolean}
   */
  checkEmail: function (email) {
    if (!email) {
      return false;
    }
    const reg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
    if (!reg.test(email)) {
      return false;
    }
    return true;
  },

  /**
   * 计算字符串字节数
   * @param  {String} str 计算的字符串
   * @param  {[int]} size4Chinese   每个汉字代表字节数
   * @return {[int]}     字节总数
   */
  countBytes: function (str, size4Chinese) {
    var str4Single = str.replace(/[\u4e00-\u9fa5]+/g, "");
    var str4Chinese = str.replace(/[^\u4e00-\u9fa5]+/g, "");
    return str4Single.length + str4Chinese.length * size4Chinese;
  },
  /**
   * 获取浏览器参数
   * @param name
   * @returns {null}
   */
  getUrlParam: function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
      return decodeURI(r[2]);
    }

    return null;
  },
  /**
   * 获取浏览器参数
   * @param name
   * @returns {null}
   */
  getUrlParam2: function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var hash = window.location.hash.split("?");
    if (hash.length > 1) {
      var r = window.location.hash.split("?")[1].match(reg);
      if (r != null) {
        return decodeURI(r[2]);
      }
    }
    return null;
  },
  /**
   * 获取浏览器参数
   * @param name url
   * @returns {null}
   */
  getUrlParam3: function (name, url) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var u = url ? url : window.location.hash;
    var hash = u.split("?");
    if (hash.length > 1) {
      var r = u.split("?")[1].match(reg);
      if (r != null) {
        return decodeURI(r[2]);
      }
    }
    return null;
  },
  concatSessionId: function (obj) {
    if (obj && !obj["s"]) {
      obj["s"] = APP.sessionId;
    }
    return obj;
  },
  clearInputFocusWhenBack: function () {
    let inputList = document.getElementsByTagName("input");
    for (let i = 0, length = inputList.length; i < length; i++) {
      inputList[i].blur();
    }
    let textareaList = document.getElementsByTagName("textarea");
    for (let i = 0, length = textareaList.length; i < length; i++) {
      textareaList[i].blur();
    }
  },
  nullValueParser: function (targetObj, key, replaceValue) {
    return this.nullValueParserByEL(targetObj, key, replaceValue);
  },
  /**
	执行表达式并返回执行结果
	@targetObj 目标对象
	@param el 'activityDetail.activityStartTime'
	@replaceValue 如果执行表达式失败返回的结果
	 */
  nullValueParserByEL: function (targetObj, el, replaceValue) {
    if (replaceValue != 0 && !replaceValue) {
      replaceValue = "--";
    }

    var keyNames = el.split(".");
    if (keyNames.length >= 2) {
      keyNames = keyNames.splice(1);
    }

    //适配数组
    var linkedKeyNames = new Array();
    for (var i = 0; i < keyNames.length; i++) {
      if (keyNames[i].indexOf("[") != -1) {
        linkedKeyNames.push(keyNames[i].substring(0, keyNames[i].indexOf("[")));
        linkedKeyNames.push(keyNames[i].substring(keyNames[i].indexOf("[") + 1, keyNames[i].length - 1));
      } else {
        linkedKeyNames.push(keyNames[i]);
      }
    }

    try {
      var result = targetObj;
      for (var i = 0; i < linkedKeyNames.length; i++) {
        result = result[linkedKeyNames[i]];
      }

      if ((result != 0 && !result) || result == "") {
        result = replaceValue;
      }
    } catch (exception) {
      result = replaceValue;
    }

    return result;
  },

  /**
   * 获取登录用户信息
   * @returns {
   *  kbShopId: "2017022700077000000026808340"
      kbSupplierId: "2088421308123132"
      role: "4"(4为店长)
      shopName: "云纵测试门店(丁家屯店)"
      userId: "20180725155733041979794275255568"
      userName: "店长AAAAAAAA"
      yzShopId: "2017022700077000000026808340"
	  yzSupplierId: "2088421308123132"
   * }
   */
  getUserInfo(loading=false) {
    return new Promise(function (resolve, reject) {
      let current = new Date();
      let userInfo = store.state.userInfo;
      let cacheTime = 10 * 60 * 1000;
      if (userInfo && userInfo.currentTime && current - userInfo.currentTime < cacheTime) {
        resolve(userInfo);
      } else {
        requestApi({
          type: "get",
          url: "/newapp/user/info.do",
          controlLoading: loading
        })
          .then(response => {
            if (response && response.success) {
              userInfo = response.resultObject;
              userInfo.currentTime = current;
              store.commit("WRITE_USER", userInfo);
              resolve(userInfo);
            } else {
              reject();
            }
          })
          .catch(err => {
            reject();
          });
      }
    });
  },
  /**
   * 获取角色和门店信息（经营分析中使用的）
   * @returns {
        isKb: false
        isWm: true
        selfShopId: "all"
        selfShopName: ""
        shopNum: 122
   * }
   */
  getRoleInfo() {
    return new Promise(function (resolve, reject) {
      let current = new Date();
      let roleInfo = store.state.roleInfo;
      let cacheTime = 10 * 60 * 1000;
      if (roleInfo && roleInfo.currentTime && current - roleInfo.currentTime < cacheTime) {
        resolve(roleInfo);
      } else {
        requestApi({
          type: "get",
          url: "/newapp/statistics/checkUserRole.do",
          controlLoading: false
        })
          .then(response => {
            if (response && response.success) {
              roleInfo = response.resultObject;
              roleInfo.currentTime = current;
              store.commit("WRITE_ROLE", roleInfo);
              resolve(roleInfo);
            } else {
              reject();
            }
          })
          .catch(err => {
            reject();
          });
      }
    });
  },
  //获取设备信息
  getDeviceInfo() {
    return new Promise(function (resolve, reject) {
      const current = new Date().getTime();
      let deviceInfo;
      try {
        deviceInfo = JSON.parse(localStorage.getItem("getCommodityList"));
      } catch (error) {

      }
      const cacheTime = 1 * 60 * 1000;
      if (deviceInfo && deviceInfo.currentTime && current - deviceInfo.currentTime < cacheTime) {
        resolve(deviceInfo.deviceList);
      } else {
        requestApi({
          type: "get",
          url: "/newapp/orderService/getCommodityList.do",
          controlLoading: false
        })
          .then(response => {
            if (response && response.success) {
              deviceInfo = { deviceList: response.resultObject, currentTime: current }
              try {
                localStorage.setItem("getCommodityList", JSON.stringify(deviceInfo));
              } catch (error) {

              }
              resolve(deviceInfo.deviceList);
            } else {
              reject();
            }
          })
          .catch(err => {
            reject();
          });
      }
    });
  },
  /*获取订单筛选项*/
  getOrderCondition() {
    return new Promise(function (resolve, reject) {
      let current = new Date();
      let orderCondition = store.state.orderCondition;
      let cacheTime = 10 * 60 * 1000;
      if (orderCondition && orderCondition.currentTime && current - orderCondition.currentTime < cacheTime) {
        resolve(orderCondition);
      } else {
        requestApi({
          type: "get",
          url: "/app/order/getOrderCondition.do",
          controlLoading: false
        })
          .then(response => {
            if (response && response.success) {
              orderCondition = response.resultObject;
              orderCondition.currentTime = current;
              store.commit("ADD_ORDER_CONDITION", orderCondition);
              resolve(orderCondition);
            } else {
              reject();
            }
          })
          .catch(err => {
            reject();
          });
      }
    });
  },
  //判断商城的商品是否为短信包
  isMessagePackage(machineType) {
    if (machineType == 22 || machineType == 23 || machineType == 24) {
      return true;
    } else {
      return false;
    }
  },
  //商品购买页面是否需要显示联系人信息
  needLinkInfo(machineType) {
    if (machineType >= 25 && machineType <= 31) {
      return true;
    } else {
      return false;
    }
  },
  //商品购买页面是否需要显示适用门店
  needShopMall(machineType) {
    /* if (machineType == 19) {
      return true;
    } else {
      return false;
    } */
    let needTypes = [19, 34, 35];
    return needTypes.includes(+machineType);
  },
  //商品购买页面是否需要显示购买数量
  needCountMall(machineType) {
    /* if (machineType != 19&&machineType != 33) {
      return true;
    } else {
      return false;
    } */
    let needTypes = [19, 33, 34, 35];
    return !needTypes.includes(+machineType);
  },
  //商品是否需要单位
  needUnitMall(machineType) {
    if (machineType == 19||(machineType == 33)) {
      return "/年";
    } else {
      return "";
    }
  },
  //商品是否需要有效期
  needExpiryTimeMall(machineType) {
    if (machineType == 19||(machineType == 33)) {
      return "1年";
    } else {
      return "";
    }
  },
  //时间戳转为日期格式
  timestampToTime(timestamp) {
    let date = new Date(timestamp);
    let Y = date.getFullYear() + "-";
    let M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
    let d = date.getDate();
    d = d < 10 ? "0" + d : d;
    d = d + " ";
    let h = date.getHours();
    h = h < 10 ? "0" + h : h;
    h = h + ":";
    let m = date.getMinutes();
    m = m < 10 ? "0" + m : m;
    m = m + ":";
    let s = date.getSeconds();
    s = s < 10 ? "0" + s : s;
    return Y + M + d + h + m + s;
  },
  formatPickerData(data, fieldText, fieldVal) {
    let list = [];
    data &&
      data.map(item => {
        let obj = {};
        if (item[fieldText]) {
          obj["value"] = item[fieldText];
          obj["id"] = item[fieldVal];
        } else {
          obj["value"] = item;
          obj["id"] = item;
        }
        list.push(obj);
      });
    return list;
  },
  milliFormat(num, n) {

    //参数说明：num 要格式化的数字 n 保留小数位

    num = String(num.toFixed(n));
    var re = /(-?\d+)(\d{3})/;

    while (re.test(num)) {

      num = num.replace(re, "$1,$2");

    }

    return num;

  },
  parseParam: function (data) {
    try {
      var tempArr = [];
      for (var i in data) {
        var key = encodeURIComponent(i);
        var value = encodeURIComponent(data[i]);
        tempArr.push(key + "=" + value);
      }
      var urlParamsStr = tempArr.join("&");
      return urlParamsStr;
    } catch (err) {
      return "";
    }
  },
  //脱敏银行卡号
  encryptionBankCardNo(cardNo) {
    if (cardNo && cardNo.length > 8) {
      let start = '';
      for (let i = 0; i < cardNo.length - 8; i++) {
        start += "*";
      }
      return cardNo.substr(0, 4) + "" + start + cardNo.substr(cardNo.length - 4, 4);
    } else {
      return cardNo;
    }
  },
  getMachineNameByType(type) {
    let name = "未知机具类型";
    if (type == 1) {
      name = "金员宝智能POS";
    }
    else if (type == 2) {
      name = "金员宝智能POS银联版";
    }
    else if (type == 3) {
      name = "扫码设备";
    }
    else if (type == 4) {
      name = "银员宝-云小盒";
    }
    else if (type == 5) {
      name = "小票打印机";
    }
    else if (type == 6) {
      name = "金员宝智慧盒子Wi-Fi版";
    }
    else if (type == 7) {
      name = "金员宝智慧盒子（Wi-Fi+4G）版";
    }
    else if (type == 8) {
      name = "【口碑版】POS基础版（不含卡）";
    }
    else if (type == 9) {
      name = "【口碑版】POS基础版（含卡）";
    }
    else if (type == 10) {
      name = "【口碑版】云小盒PLUS-Wi-Fi版";
    }
    else if (type == 11) {
      name = "【口碑版】云小盒";
    }
    else if (type == 12) {
      name = "【口碑版】小票打印机";
    }
    else if (type == 13) {
      name = "【口碑版】扫码枪";
    }
    else if (type == 14) {
      name = "一年流量卡";
    }
    else if (type == 15) {
      name = "【口碑版】一年流量卡";
    }
    else if (type == 16) {
      name = "【口碑版】云小盒PLUS（Wi-Fi+4G版）";
    }
    else if (type == 17) {
      name = "码先声Ι";
    } else if (type == 18) {
      name = "码卡龙";
    } else if (type == 19) {
      name = "小程序";
    } else if (type == 20) {
      name = "快小盒";
    } else if (type == 32) {
      name = "快小盒4G";
    } else if (type == 21) {
      name = "码先声Ⅱ";
    } else if(type == 37) {
      name = "码先声Ⅲ";
    }else if(type == 38) {
      name = "快小盒刷卡版";
    } else if(type == 39) {
      name = "如意";
    }else if(type == 40) {
      name = "E团火双屏机";
    } else if(type == 41) {
      name = "蜻蜓F4";
    }else if(type == 42) {
      name = "蜻蜓F4plus";
    }else if(type == 50) {
      name = "中云音箱";
    }else if(type == 51) {
      name = "金多多NS20S音箱";
    }else if(type == 54) {
      name = "智能POS-N910";
    }else if(type == 55) {
      name = "同福NS20S云音箱";
    }else if(type == 57) {
      name = "金多多天喻CS20音箱";
    }else if(type == 58) {
      name = "同福天喻CS20音箱";
    }else if(type == 59) {
      name = "金多多博实结CG10音箱";
    }else if(type == 60) {
      name = "同福博实结CG10音箱";
    }
    return name;
    // const names = {
    //   1: '金员宝智能POS',
    //   2: '金员宝智能POS银联版',
    //   3: '扫码设备'
    // }
    // return names[type] || '未知机具类型';
  },
  //保留两位小数(v：传进来的金额,isMinus：是否需要负号,isRmb：是否需要¥)
  moneyFormate(v, isMinus, isRmb) {
    const minus = isMinus ? "-" : "";
    const rmb = isRmb ? "¥" : "";
    if (isNaN(v) || v == null || undefined == v) {
      return "--";
    } else if (v == 0) {
      return "0.00";
    }
    else {
      return minus + "" + rmb + "" + Number(v).toFixed(2);
    }
  },
  //返现方式
  marketTypeFormate(marketType) {
    let v = "";
    if (marketType == 1) {
      v = "消费返";
    } else if (marketType == 2) {
      v = "新客返";
    } else if (marketType == 3) {
      v = "首单返";
    } else if (marketType == 4) {
      v = "阶梯返";
    }
    return v;
  },
  devicePic(machineType) {
    let type = "";
    if (machineType == 1 || machineType == 2 || machineType == 8 || machineType == 9) {
      type = "zhinengpos.png";
    } else if (machineType == 3 || machineType == 13) {
      type = "saomaqiang.png";
    } else if (machineType == 4) {
      type = "yunxiaohe.png";
    } else if (machineType == 5 || machineType == 12) {
      type = "xiaopiaodayinji.png";
    } else if (machineType == 6 || machineType == 7 || machineType == 10 || machineType == 16) {
      type = "yunxiaoheplus.png";
    } else if (machineType == 14 || machineType == 15) {
      type = "liuliangka.jpg";
    } else if (machineType == 17) {
      type = "maxiansheng.png";
    } else if (machineType == 18) {
      type = "makalong.png";
    } else if (machineType == 19) {
      type = "huiyuanguanli.png";
    } else if (machineType == 20) {
      type = "kuaixiaohe.png";
    } else if (machineType == 32) {
      type = "kuaixiaohe4g.png";
    } else if (machineType == 21) {
      type = "maxiansheng2.png";
    } else if (machineType == 22 || machineType == 23 || machineType == 24) {
      type = "duanxin.png";
    } else if (machineType == 25) {
      type = "dav1.png";
    } else if (machineType == 26) {
      type = "dav2.png";
    } else if (machineType == 27) {
      type = "dav3.png";
    } else if (machineType == 28) {
      type = "makalongpic1.png";
    } else if (machineType == 29) {
      type = "makalongpic2.png";
    } else if (machineType == 30) {
      type = "jiangxin1.png";
    } else if (machineType == 31) {
      type = "jiangxin2.png";
    }
    else {
      type = "defaultMachine.png";
    }
    return type;
  },
  //数组中是否包含重复数据(如果是对象数组 field表示要比较的对象字段名)
  repeatInArray(arr, field) {
    arr = JSON.parse(JSON.stringify(arr));
    if (arr.length < 2) {
      return false;
    }
    const nary = arr.sort((a, b) => {
      if (field) {
        return a[field] - b[field];
      } else {
        return a - b;
      }
    });
    for (let i = 0; i < nary.length; i++) {
      if (i + 1 >= nary.length) {
        break;
      }
      else if (field && nary[i][field] == nary[i + 1][field]) {
        return true;
      } else if (!field && nary[i] == nary[i + 1]) {
        return true;
      }
    }
    return false;
  },
  bandCardTypeFormate(type){
    let v=type;
    if(type==1){
      v="信用卡";
    }else if(type==2){
      v="储蓄卡";
    }
    return v;
  },
  weekFormate(weekData){
    const weekMap={
      1:"一",
      2:"二",
      3:"三",
      4:"四",
      5:"五",
      6:"六",
      7:"日",
    };
    let v="星期";
    for (let index = 0; index < weekData.length; index++) {
      let split=index==weekData.length-1?"":"、";
      v+=weekMap[weekData[index]]+split;
    }
    return v;
  },
  timeForamte(timeList){
    let v="";
    for (let index = 0; index < timeList.length; index++) {
      let split=index==timeList.length-1?"":"、";
      let s= this.getHHMM(timeList[index].startTime);
      let e= this.getHHMM(timeList[index].endTime);
      v+=s+"~"+e+split;
    }
    return v;
  },
  getHHMM(timespan){
    let hours = parseInt((timespan % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    let minutes = parseInt((timespan % (1000 * 60 * 60)) / (1000 * 60));
    hours = hours < 10 ? ('0' + hours) : hours;
    minutes = minutes < 10 ? ('0' + minutes) : minutes;
    return hours + ":" + minutes;
  },
};

window.APP.sessionId = window.APP.sessionId || window.CommonUtil.getUrlParam("s") || window.CommonUtil.getUrlParam2("s") ||"9681b3a9895040efa3f096aaeca437d0";
window.APP.AndroidSDK = window.APP.AndroidSDK || window.CommonUtil.getUrlParam("SDK") || window.CommonUtil.getUrlParam2("SDK");//d9b9f7124f8a4464814308671a027a1d
window.APP.statusBarHeight = window.CommonUtil.getUrlParam("statusBarHeight") || window.CommonUtil.getUrlParam2("statusBarHeight");//9681b3a9895040efa3f096aaeca437d0
let serverUrl = window.APP.serverUrl || window.CommonUtil.getUrlParam("url") || window.CommonUtil.getUrlParam2("url") || config.serverUrl;
serverUrl = decodeURIComponent(serverUrl);
if (serverUrl.endsWith('/')) {
  window.APP.serverUrl = serverUrl;
} else {
  window.APP.serverUrl = serverUrl + '/';
}
if (!window.APP.urlParam) {
  window.APP.urlParam = window.location.href.split("?")[1];
}
window.DateUtil = {
  /**字符串日期转换为Date;*/
  str2Date: function (dateStr) {
    var dr = dateStr.split("-");
    return new Date(dr[0], parseInt(dr[1]) - 1, dr[2]);
  },
  /**
	获取日期的YYYYMMDD格式
	*/
  getDateYYYYMMDD: function (date) {
    return this.format(date, "yyyyMMdd");
  },
  getDateYYYYMM: function (date) {
    return this.format(date, "yyyyMM");
  },
  getDateTime: function (date) {
    return this.format(date);
  },
  /**
	获取日期的YYYY-MM-DD格式
	**/
  getDateFormat: function (date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    if (month < 10) {
      month = "0" + month;
    }
    if (day < 10) {
      day = "0" + day;
    }

    return year + "-" + month + "-" + day;
  },
  /**
	获取日期的YYYY/MM/DD格式
	**/
  getDateFormat2: function (date) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    if (month < 10) {
      month = "0" + month;
    }
    if (day < 10) {
      day = "0" + day;
    }

    return year + "/" + month + "/" + day;
  },
  /**
	翻日历
	*/
  addDays: function (date, days) {
    var time = date.getTime();
    var addTimes = days * 24 * 3600 * 1000;
    date.setTime(time + addTimes);
    return date;
  },

  /**
	 * @param date 时间，Date or 时间戳，默认当前时间
	 * @param pattern 转换格式，默认yyyy-MM-dd hh:mm:ss
	 * @return string
	 *
	<p>对Date的扩展，将 Date 转化为指定格式的String
	月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
	年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
	例子：
	(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
	(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18</p>
	*/
  format: function (date, pattern) {
    Date.prototype.Format = function (fmt) {
      //author: meizz
      var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        S: this.getMilliseconds() //毫秒
      };
      if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
      return fmt;
    };

    if (!pattern) {
      pattern = "yyyy-MM-dd hh:mm:ss";
    }
    if (!date) {
      date = new Date();
    }
    if (typeof date === "number") {
      return new Date(date).Format(pattern);
    } else {
      return date.Format(pattern);
    }
  },
  compareDate: function (datestr1, datestr2) {
    return Date.parse(datestr1.replace(/-/g, "/")) > Date.parse(datestr2.replace(/-/g, "/"));
  }
};
